//
//  OAuthViewController.swift
//  WeiBo
//
//  Created by LTX on 2016/11/7.
//  Copyright © 2016年 LTX. All rights reserved.
//

import UIKit
import SVProgressHUD


class OAuthViewController: UIViewController {
    
    //控件属性
    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置导航栏
        setupNavigationBar()
        
        // 加载网页
        loadWebView()
        
    }


}


// MARK:- 设置UI
extension OAuthViewController{
    
   fileprivate func setupNavigationBar()  {
        
        //设置左标题
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(cancle))
        
        //设置右标题
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(fillClick))
        
        // 设置标题
        title = "登录授权"
    }
    
    
    // 设置webView
    fileprivate func loadWebView(){
    
        //字符串
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect_uri)"
        
       //URL
        guard  let url = NSURL(string: urlString) else {
            return
        }
        
        //URLRequest
        let URLRequest = NSURLRequest(url: url as URL)
        
        webView.loadRequest(URLRequest as URLRequest)
        
    }

}



// MARK:- 监听事件
extension OAuthViewController{
    
    //关闭登录
    func cancle()  {
        navigationController?.dismiss(animated: true, completion: nil)
    }
    
    //填充密码
    func fillClick()  {
        print("填充")
      //  https://api.weibo.com/oauth2/authorize?client_id=
        
        //js代码
        let jsCode = "document.getElementById('userId').value='nslog@sina.cn';document.getElementById('passwd').value='13865899315';"
        
        //执行js代码
        webView.stringByEvaluatingJavaScript(from: jsCode)
    }
    

}


// MARK:- 代理事件
extension OAuthViewController: UIWebViewDelegate{
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    //拦截网络请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard  let url = request.url else {
            return true
        }
        
        //url转成字符串
        let urlString = url.absoluteString
        
        guard urlString.contains("code=") else {
            return true
        }
        
        //取出code
        let code = urlString.components(separatedBy: "code=").last!
        
        print(urlString)
        
        print("code=\(code)")
        
        
        //获取AccessToken
        loadAccessToken(code: code)
        
        return false
        

        
        
        
    }
    
}


// MARK:- 网络请求
extension OAuthViewController{

    // MARK:- post请求
    func loadAccessToken(code: String) {
        
            NetworkTools.shareInstance.loadAccessToken(code: code) { (result, error) in
            
                if error != nil{
                    print(error)
                    return
                }
                
                print(result)
                
                guard  let accessDic = result else{
                    print("没有数据")
                    return
                }
                
                //用户模型
                let userInfo = userAccount(dic: accessDic)
                
                print("用户的AccessToken\(userInfo)")
                
                self.loadUserInfo(user: userInfo)
                
        }
    
    }
    
    
    //获取用户信息
    func loadUserInfo(user : userAccount) {
        
        guard let accessToken = user.access_token else {
            return;
        }
        
        guard let uid = user.uid else {
            return
        }
        
        NetworkTools.shareInstance.loadUserInfo(accessToken: accessToken, uid : uid) { (result, error) in
            
            if error != nil {
                return
            }
            
            // 用户信息结果
            
            guard let userInfoDic = result else{
            print("没有用户信息数据")
            return
            }
            
            user.screen_name = userInfoDic["screen_name"] as?String
            user.avatar_large = userInfoDic["avatar_large"] as?String
            
            // 4.将account对象保存
            // 4.1.获取沙盒路径
//            var accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
//            accountPath = (accountPath as NSString).appendingPathComponent("accout.plist")
//            print(accountPath)
            
            // 4.2.保存对象
            NSKeyedArchiver.archiveRootObject(user, toFile: UserAccountViewModel.shareIntance.accountPath)
            
            //设置有值的account到单例中
            UserAccountViewModel.shareIntance.account = user
            
            //退出当前控制并显示欢迎界面
           self.dismiss(animated: false, completion: {
                
                UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
                
            })
            
        }
    }


}

